/**
 * 区域绘制相关功能 Composable
 * 包含2D/3D区域绘制、编辑等功能
 */
import { ref } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import { toLatLng, clearEntityLayer } from "../assets/cesiumFunction/Map"
import { areaLayerName } from "../assets/cesiumFunction/LayerName"
import { useMapCore } from './useMapCore'

export function useAreaDrawing() {
  // 获取地图核心功能
  const { GodViewer, tracker } = useMapCore()
  // 响应式数据
  const areaRecord = ref([])
  const lineRecord = ref([])
  const lineObjId = ref(null) // 保存当前线的 objId
  const areaObjId = ref(null) // 保存当前区域的 objId
  const polygonEntity = ref(null)
  const mouseMoveHandler = ref(null)
  const mouseClickHandler = ref(null)

  //=============2D区域绘制===============
  /**
   * 绘制区域
   */
  const drawArea = () => {
    if (!tracker.value) {
      console.error('tracker 未初始化，请确保地图已正确加载')
      return
    }
    
    tracker.value.trackPolygon(async (positions) => {
      const objId = uuidv4()
      areaRecord.value = positions
      showArea(objId, positions)
    },
      () => {
        cosole.log('取消绘制')
      })
  }

  /**
   * 重新绘制区域
   */
  const redrawArea = () => {
    if (!tracker.value) {
      console.error('tracker 未初始化，请确保地图已正确加载')
      return
    }
    
    clearEntityLayer(GodViewer.value, areaLayerName)
    
    tracker.value.trackPolygon(async (positions) => {
      const objId = uuidv4()
      areaRecord.value = positions
      showArea(objId, positions)
    },
      () => {
        const objId = uuidv4()
        showArea(objId, areaRecord.value)
      })
  }

  /**
   * 编辑区域
   */
  const editArea = () => {
    if (!tracker.value) {
      console.error('tracker 未初始化，请确保地图已正确加载')
      return
    }
    clearEntityLayer(GodViewer.value, areaLayerName)
    
    tracker.value.polygonDrawer.showModifyPolygon(areaRecord.value, async (positions) => {
      const objId = uuidv4()
      areaRecord.value = positions
      showArea(objId, positions)
    },
      () => {
        const objId = uuidv4()
        showArea(objId, areaRecord.value)
      })
  }

  /**
   * 显示区域
   */
  const showArea = (areaId, positions, height = 0) => {
    const material = new Cesium.ColorMaterialProperty(
      Cesium.Color.fromCssColorString('#ff0').withAlpha(0.5)
    )
    const outlineMaterial = new Cesium.PolylineDashMaterialProperty({
      dashLength: 16,
      color: Cesium.Color.fromCssColorString('#00f').withAlpha(0.7)
    })
    
    const outlinePositions = [].concat(positions)
    outlinePositions.push(positions[0])
    
    const entity = GodViewer.value.entities.add({
      layerId: areaLayerName,
      objId: areaId,
      shapeType: "Polygon",
      polyline: {
        positions: outlinePositions,
        clampToGround: true,
        width: 2,
        material: outlineMaterial,
        height: height,
      },
      polygon: new Cesium.PolygonGraphics({
        hierarchy: positions,
        asynchronous: false,
        material: material,
        height: height,
      })
    })
    
    areaRecord.value.map((position, index) => {
      GodViewer.value.entities.add({
        layerId: areaLayerName,
        objId: areaId,
        shapeType: "Point",
        position: position,
        billboard: {
          image: "images/circle_red.png",
          eyeOffset: new Cesium.ConstantProperty(new Cesium.Cartesian3(0, 0, -500)),
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        },
        label: {
          text: `${index + 1}`,
          font: '15pt Helvetica',
          fillColor: Cesium.Color.WHITE,
          outlineColor: Cesium.Color.DARKBLUE,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          verticalOrigin: Cesium.VerticalOrigin.TOP,
          pixelOffset: new Cesium.Cartesian2(-10, 10)
        }
      })
    })
    
    return entity
  }

  //=============立体航线绘制===============
  /**
   * 绘制区域
   */
  const drawBuildingArea = (height) => {
    if (!tracker.value) {
      console.error('tracker 未初始化，请确保地图已正确加载')
      return
    }
    
    clearEntityLayer(GodViewer.value, areaLayerName)
    
    tracker.value.trackPolygon(async (positions) => {
      const objId = uuidv4()
      areaObjId.value = objId // 保存 objId
      areaRecord.value = positions
      showBuildingArea(objId, positions, height)
    },
      () => {
        if(areaRecord.value) {
          const objId = uuidv4()
          areaObjId.value = objId // 保存 objId
          showBuildingArea(objId, areaRecord.value, height)
        }
      })
  }

  /**
   * 编辑区域
   */
  const editBuildingArea = (height) => {
    if (!tracker.value) {
      console.error('tracker 未初始化，请确保地图已正确加载')
      return
    }
    clearEntityLayer(GodViewer.value, areaLayerName)
    
    tracker.value.polygonDrawer.showModifyPolygon(areaRecord.value, async (positions) => {
      const objId = uuidv4()
      areaObjId.value = objId // 保存 objId
      areaRecord.value = positions
      showBuildingArea(objId, positions, height)
    },
      () => {
        const objId = uuidv4()
        areaObjId.value = objId // 保存 objId
        showBuildingArea(objId, areaRecord.value, height)
      })
  }

  /**
   * 只编辑建筑物高度
   */
  const editBuildingHeight = (height) => {
    if (areaRecord.value && areaRecord.value.length > 0 && areaObjId.value) {
      clearEntityLayer(GodViewer.value, areaLayerName)
      // 使用保存的 objId，保留现有的 objId 和 positions，只更新高度
      showBuildingArea(areaObjId.value, areaRecord.value, height)
    } else {
      console.warn('无法编辑建筑物高度：区域数据或 objId 不存在')
    }
  }
  
  /**
   * 显示区域
   */
  const showBuildingArea = (areaId, positions, height = 0) => {
    const material = new Cesium.ColorMaterialProperty(
      Cesium.Color.fromCssColorString('#ff0').withAlpha(0.5)
    )
    
    const outlinePositions = [].concat(positions)
    outlinePositions.push(positions[0])
    
    const entity = GodViewer.value.entities.add({
      layerId: areaLayerName,
      objId: areaId,
      shapeType: "Polygon",
      polygon: new Cesium.PolygonGraphics({
        hierarchy: positions,
        asynchronous: false,
        material: material,
        outline: true,
        outlineColor: Cesium.Color.fromCssColorString('#00f').withAlpha(0.7),
        arcType: Cesium.ArcType.RHUMB,
        extrudedHeight: height, 
    }),
    })
    
    return entity
  }

//=============沿线巡检绘制===============
  /**
   * 创建缓冲区多边形
   * @param {Array} positions - 原始线段的点位置数组
   * @param {number} buffer - 缓冲区半径（米）
   * @returns {Array} 缓冲区多边形的点位置数组
   */
  const createBufferPolygon = (positions, buffer) => {
    if (positions.length < 2) return positions

    const bufferPositions = []
    const leftSide = []  // 左侧轮廓点
    const rightSide = [] // 右侧轮廓点
    
    // 为每个线段创建缓冲区
    for (let i = 0; i < positions.length - 1; i++) {
      const start = positions[i]
      const end = positions[i + 1]
      
      // 计算线段方向向量
      const direction = Cesium.Cartesian3.subtract(end, start, new Cesium.Cartesian3())
      const length = Cesium.Cartesian3.magnitude(direction)
      
      if (length > 0) {
        // 归一化方向向量
        const normalizedDirection = Cesium.Cartesian3.normalize(direction, new Cesium.Cartesian3())
        
        // 计算垂直向量（通过叉积）
        const up = Cesium.Cartesian3.UNIT_Z
        const right = Cesium.Cartesian3.cross(normalizedDirection, up, new Cesium.Cartesian3())
        const normalizedRight = Cesium.Cartesian3.normalize(right, new Cesium.Cartesian3())
        
        // 计算缓冲区的四个角点
        const halfBuffer = buffer / 2
        const offset1 = Cesium.Cartesian3.multiplyByScalar(normalizedRight, halfBuffer, new Cesium.Cartesian3())
        const offset2 = Cesium.Cartesian3.multiplyByScalar(normalizedRight, -halfBuffer, new Cesium.Cartesian3())
        
        const p1 = Cesium.Cartesian3.add(start, offset1, new Cesium.Cartesian3())  // 右侧起点
        const p2 = Cesium.Cartesian3.add(start, offset2, new Cesium.Cartesian3())  // 左侧起点
        const p3 = Cesium.Cartesian3.add(end, offset1, new Cesium.Cartesian3())    // 右侧终点
        const p4 = Cesium.Cartesian3.add(end, offset2, new Cesium.Cartesian3())    // 左侧终点
        
        // 分别收集左右两侧的点
        if (i === 0) {
          // 第一个线段，添加起点
          rightSide.push(p1)
          leftSide.push(p2)
        }
        // 添加终点
        rightSide.push(p3)
        leftSide.push(p4)
      }
    }
    
    // 按照一笔画的顺序组合点：右侧轮廓 + 左侧轮廓（反向）
    bufferPositions.push(...rightSide)
    bufferPositions.push(...leftSide.reverse())
    
    // 闭合多边形
    if (bufferPositions.length > 0) {
      bufferPositions.push(bufferPositions[0])
    }
    
    return bufferPositions
  }

    /**
   * 重新绘制线
   */
    const drawLine = (buffer) => {
      if (!tracker.value) {
        console.error('tracker 未初始化，请确保地图已正确加载')
        return
      }
      
      clearEntityLayer(GodViewer.value, areaLayerName)
      
      tracker.value.trackPolyline(async (positions) => {
        const objId = uuidv4()
        lineObjId.value = objId // 保存 objId
        lineRecord.value = positions
        showLine(objId, positions, buffer)
      },
        () => {
          if(lineRecord.value) {
            const objId = uuidv4()
            lineObjId.value = objId // 保存 objId
            showLine(objId, lineRecord.value, buffer)
          }
        })
    }

      /**重新根据新的buffer绘制线 */
  const editLineBuffer = (buffer) => {
    if (lineRecord.value && lineObjId.value) {
      clearEntityLayer(GodViewer.value, areaLayerName)
      // 使用保存的 objId，保留现有的 objId 和 positions
      showLine(lineObjId.value, lineRecord.value, buffer)
    }
  }
  
    /**
     * 编辑线
     */
    const editLine = (buffer) => {
      if (!tracker.value) {
        console.error('tracker 未初始化，请确保地图已正确加载')
        return
      }
      clearEntityLayer(GodViewer.value, areaLayerName)
      
      tracker.value.polylineDrawer.showModifyPolyline(lineRecord.value, async (positions) => {
        const objId = uuidv4()
        lineObjId.value = objId // 保存 objId
        lineRecord.value = positions
        showLine(objId, positions, buffer)
      },
        () => {
          const objId = uuidv4()
          lineObjId.value = objId // 保存 objId
          showLine(objId, lineRecord.value, buffer)
        })
    }

  const showLine = (lineId, positions, buffer) => {
    // 1. 绘制点
    positions.forEach((position, index) => {
      GodViewer.value.entities.add({
        layerId: areaLayerName,
        objId: lineId,
        shapeType: "Point",
        position: position,
        billboard: {
          image: "images/circle_red.png",
          eyeOffset: new Cesium.ConstantProperty(new Cesium.Cartesian3(0, 0, -500)),
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        },
        label: {
          text: `${index + 1}`,
          font: '15pt Helvetica',
          fillColor: Cesium.Color.WHITE,
          outlineColor: Cesium.Color.DARKBLUE,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          verticalOrigin: Cesium.VerticalOrigin.TOP,
          pixelOffset: new Cesium.Cartesian2(-10, 10)
        }
      })
    })

    // 2. 绘制点连成的线
    const lineEntity = GodViewer.value.entities.add({
      layerId: areaLayerName,
      objId: lineId,
      shapeType: "Polyline",
      polyline: {
        positions: positions,
        clampToGround: true,
        width: 3,
        material: new Cesium.PolylineDashMaterialProperty({
          dashLength: 16,
          color: Cesium.Color.fromCssColorString('#00f').withAlpha(0.8)
        })
      }
    })

    // 3. 以buffer为缓冲区半径绘制polygon面
    if (buffer && buffer > 0) {
      // 创建缓冲区多边形
      const bufferPositions = createBufferPolygon(positions, buffer)
      
      GodViewer.value.entities.add({
        layerId: areaLayerName,
        objId: lineId,
        shapeType: "Polygon",
        polygon: {
          hierarchy: bufferPositions,
          asynchronous: false,
          material: new Cesium.ColorMaterialProperty(
            Cesium.Color.fromCssColorString('#ff0').withAlpha(0.3)
          ),
          outline: true,
          outlineColor: Cesium.Color.fromCssColorString('#ff0').withAlpha(0.8)
        }
      })
    }

    return lineEntity
  }

  //=============斜面区域绘制===============
  /**
   * 绘制3D平面
   */
  const draw3DPlane = (maxHeight) => {
    if (!tracker.value) {
      console.error('tracker 未初始化，请确保地图已正确加载')
      return
    }
    
    let point1 = null
    let point2 = null
    let point3 = null
    areaRecord.value = []
    clearEntityLayer(GodViewer.value, areaLayerName)
    
    if (!point1) {
      tracker.value.trackPoint(
        async (position) => {
          const LatLon = toLatLng(position)
          point1 = Cesium.Cartesian3.fromDegrees(LatLon['longitude'], LatLon['latitude'], 0)
          add3DPoint(position, '基准点1')
          
          tracker.value.trackPoint(
            async (position) => {
              const LatLon = toLatLng(position)
              point2 = Cesium.Cartesian3.fromDegrees(LatLon['longitude'], LatLon['latitude'], 0)
              add3DPoint(position, '基准点2')
              
              tracker.value.trackPoint(
                async (position) => {
                  const LatLon = toLatLng(position)
                  point3 = Cesium.Cartesian3.fromDegrees(LatLon['longitude'], LatLon['latitude'], maxHeight)
                  
                  GodViewer.value.entities.add({
                    layerId: areaLayerName,
                    shapeType: "Point",
                    position: point3,
                    billboard: {
                      image: "images/circle_red.png",
                    },
                  })
                  
                  const temp1 = Cesium.Cartesian3.subtract(point3, point2, new Cesium.Cartesian3())
                  const point4 = Cesium.Cartesian3.add(point1, temp1, new Cesium.Cartesian3())
                  
                  areaRecord.value.push(point1)
                  areaRecord.value.push(point2)
                  areaRecord.value.push(point3)
                  areaRecord.value.push(point4)
                  
                  if (areaRecord.value) {
                    const objId = uuidv4()
                    show3DArea(objId, areaRecord.value)
                  }
                }
              )
            }
          )
        }
      )
    }
  }

  /**
   * 添加3D点
   */
  const add3DPoint = (position, labelText) => {
    GodViewer.value.entities.add({
      layerId: areaLayerName,
      shapeType: "Point",
      position: position,
      billboard: {
        image: "images/circle_red.png",
        eyeOffset: new Cesium.ConstantProperty(new Cesium.Cartesian3(0, 0, -500)),
      },
      label: {
        text: labelText,
        font: '15pt Helvetica',
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.DARKBLUE,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        verticalOrigin: Cesium.VerticalOrigin.TOP,
        pixelOffset: new Cesium.Cartesian2(-10, 10)
      }
    })
  }

  /**
   * 显示3D区域
   */
  const show3DArea = (areaId, positions) => {
    const material = new Cesium.ColorMaterialProperty(
      Cesium.Color.fromCssColorString('#ff0').withAlpha(0.5)
    )
    const outlineMaterial = new Cesium.PolylineDashMaterialProperty({
      dashLength: 16,
      color: Cesium.Color.fromCssColorString('#00f').withAlpha(0.7)
    })
    
    const outlinePositions = [].concat(positions)
    outlinePositions.push(positions[0])

    const entity = GodViewer.value.entities.add({
      layerId: areaLayerName,
      objId: areaId,
      shapeType: "Polygon",
      polyline: {
        positions: outlinePositions,
        width: 2,
        material: outlineMaterial,
      },
      polygon: {
        hierarchy: positions,
        perPositionHeight: true,
        asynchronous: false,
        material: material,
      }
    })
    
    areaRecord.value.map((position, index) => {
      GodViewer.value.entities.add({
        layerId: areaLayerName,
        objId: areaId,
        shapeType: "Point",
        position: position,
        billboard: {
          image: "images/circle_red.png",
          eyeOffset: new Cesium.ConstantProperty(new Cesium.Cartesian3(0, 0, -500)),
        },
        label: {
          text: `${index + 1}`,
          font: '15pt Helvetica',
          fillColor: Cesium.Color.WHITE,
          outlineColor: Cesium.Color.DARKBLUE,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          verticalOrigin: Cesium.VerticalOrigin.TOP,
          pixelOffset: new Cesium.Cartesian2(-10, 10)
        }
      })
    })
    
    return entity
  }



  /**
   * 编辑3D平面高度
   */
  const edit3DPlane = (maxHeight) => {
    if (areaRecord.value.length > 0) {
      clearEntityLayer(GodViewer.value, areaLayerName)
      const LatLon2 = toLatLng(areaRecord.value[2])
      areaRecord.value[2] = Cesium.Cartesian3.fromDegrees(LatLon2['longitude'], LatLon2['latitude'], maxHeight)
      const LatLon3 = toLatLng(areaRecord.value[3])
      areaRecord.value[3] = Cesium.Cartesian3.fromDegrees(LatLon3['longitude'], LatLon3['latitude'], maxHeight)
      const objId = uuidv4()
      show3DArea(objId, areaRecord.value)
    }
  }

  /**
   * 编辑3D绘制
   */
  const edit3DDraw = (maxHeight) => {
    if (areaRecord.value) {
      clearEntityLayer(GodViewer.value, areaLayerName)

      mouseMoveHandler.value = new Cesium.ScreenSpaceEventHandler(GodViewer.value.scene.canvas)
      mouseMoveHandler.value.setInputAction((movement) => {
        const cartesian = GodViewer.value.camera.pickEllipsoid(movement.endPosition, GodViewer.value.scene.globe.ellipsoid)
        if (cartesian) {
          const LatLon2 = toLatLng(cartesian)
          areaRecord.value[2] = Cesium.Cartesian3.fromDegrees(LatLon2['longitude'], LatLon2['latitude'], maxHeight)
          const temp1 = Cesium.Cartesian3.subtract(areaRecord.value[2], areaRecord.value[1], new Cesium.Cartesian3())
          areaRecord.value[3] = Cesium.Cartesian3.add(areaRecord.value[0], temp1, new Cesium.Cartesian3())
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

      const objId = uuidv4()
      polygonEntity.value = GodViewer.value.entities.add({
        layerId: areaLayerName,
        shapeType: "Polygon",
        polygon: {
          hierarchy: new Cesium.CallbackProperty(() => {
            return new Cesium.PolygonHierarchy(areaRecord.value)
          }, false),
          perPositionHeight: true,
          asynchronous: false,
          material: new Cesium.ColorMaterialProperty(
            Cesium.Color.fromCssColorString('#ff0').withAlpha(0.5)
          )
        },
        polyline: {
          positions: new Cesium.CallbackProperty(() => {
            const outlinePositions = [...areaRecord.value]
            outlinePositions.push(areaRecord.value[0])
            return outlinePositions
          }, false),
          width: 2,
          material: new Cesium.PolylineDashMaterialProperty({
            dashLength: 16,
            color: Cesium.Color.fromCssColorString('#00f').withAlpha(0.7)
          })
        }
      })

      mouseClickHandler.value = new Cesium.ScreenSpaceEventHandler(GodViewer.value.scene.canvas)
      mouseClickHandler.value.setInputAction(() => {
        mouseClickHandler.value.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
        mouseMoveHandler.value.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
        
        if (polygonEntity.value) {
          GodViewer.value.entities.remove(polygonEntity.value)
          polygonEntity.value = null
        }
        show3DArea(objId, areaRecord.value)
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    }
  }

  // 清理函数
  const cleanup = () => {
    if (mouseMoveHandler.value) {
      mouseMoveHandler.value.destroy()
      mouseMoveHandler.value = null
    }
    if (mouseClickHandler.value) {
      mouseClickHandler.value.destroy()
      mouseClickHandler.value = null
    }
    if (polygonEntity.value) {
      polygonEntity.value = null
    }
  }

  return {
    // 响应式数据
    areaRecord,
    lineRecord,
    lineObjId,
    areaObjId,
    polygonEntity,
    mouseMoveHandler,
    mouseClickHandler,
    
    // 方法
    drawArea,
    redrawArea,
    editArea,
    showArea,
    showLine,
    editLine,
    drawLine,
    editLineBuffer,
    draw3DPlane,
    add3DPoint,
    show3DArea,
    edit3DPlane,
    edit3DDraw,
    drawBuildingArea,
    editBuildingArea,
    editBuildingHeight,
    cleanup
  }
}